<?php
class xpdo{
	public $query;
	public $data;
	function __construct(){
		try{
			$driver_opts=array(PDO::ATTR_AUTOCOMMIT=>0, PDO::ATTR_PERSISTENT=>false);	
			$this->pdo=new PDO(DSN, USERNAME, PASSWORD, $driver_opts);
			$this->pdo->setAttribute(PDO::ATTR_ERRMODE,  PDO::ERRMODE_WARNING);
			$this->pdo->exec('set names utf8');
		}catch(PDOException $e){
			echo "数据库连接失败：".$e->getMessage();
			exit;
		}	
	}
	private function setTable($tabName){
		$cachefile='table/'.$tabName.'.php';
		if(file_exists($cachefile)){
			$json=ltrim(file_get_contents($cachefile),'<?php //');
			$fieldList=(array)json_decode($json, true);
			return $fieldList;
		}else{
			$stmt=$this->pdo->prepare("desc {$tabName}");
			$stmt->execute();
			$fields=array();
			while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
				$fields[]=strtolower($row['Field']);
			}		
			file_put_contents($cachefile, '<?php //'.json_encode($fields));
			return $fields;
		}
	}
	private function remove_arr($fieldList,$data){
		$arr=array();
		foreach($data as $key=>$value){
			if(in_array($key,$fieldList)){
				$arr[0][$key]=':'.$key;
				$arr[1][$key]=$value;
			}
		}
		return $arr;
	}
	function ready($query,$data=array()){
		$method=strtolower(substr($query,0,6));
		
		switch ($method){
			case 'insert':
			$tablename=preg_replace("/insert into(?:\s)*(?:`)?([a-z0-9_-]+)(?:`)?(?:\s)*.*/is","\\1",$query);
			$fieldList=$this->setTable($tablename);
			$arr=$this->remove_arr($fieldList,$data);
			$this->data=$arr[1];
			$queryvalues='(`'.implode('`,`', array_keys($arr[0])).'`) values ('.implode(',', array_values($arr[0])). ')';
			$this->query=sprintf($query,$queryvalues);
			break;
			case 'update':
			$tablename=preg_replace("/update(?:\s)*(?:`)?([a-z0-9_-]+)(?:`)?(?:\s)*.*/is","\\1",$query);
			$fieldList=$this->setTable($tablename);
			$arr=$this->remove_arr($fieldList,$data);
			$this->data=$arr[1];
			
			foreach ($arr[0] as $k=>$v) {
				$queryvalues .="`{$k}`={$v},";
			}
			$queryvalues=rtrim($queryvalues, ',');
			$this->query=sprintf($query,$queryvalues);
			break;
			case 'delete':
			$this->query=$query;
			$this->data=$data;
			break;
			case 'select':
			$this->query=$query;
			$this->data=$data;
			break;
			default:
			exit;
			break;
		}
		return $this;
	}
	function insert(){
		$stmt=$this->pdo->prepare($this->query);
		if($stmt->execute($this->data)){
			return $this->pdo->lastInsertId();	
		}else{
			echo "<script>alert('数据插入失败！');</script>";
			exit;
		}	
	}
	function update($where=array()){
		$stmt=$this->pdo->prepare($this->query);
		if($stmt->execute(array_merge($this->data,$where))){
			return true;
		}else{
			echo "<script>alert('数据修改失败！');</script>";
			exit;
		}			
	}
	function delete($where=array()){
		$stmt=$this->pdo->prepare($this->query);
		if($stmt->execute(array_merge($this->data,$where))){
			return true;
		}else{
			echo "<script>alert('数据删除失败！');</script>";
			exit;
		}		
	}
	function select($where=array()){
		$stmt=$this->pdo->prepare($this->query);
		$stmt->execute(array_merge($this->data,$where));
		if($result=$stmt->fetch(PDO::FETCH_ASSOC)){
			return $result;
		}else{
			echo "<script>alert('数据查询失败！');</script>";
			exit;
		}
	}
	function mselect($where=array()){
		$stmt=$this->pdo->prepare($this->query);
		$stmt->execute(array_merge($this->data,$where));
		if($result=$stmt->fetchAll(PDO::FETCH_ASSOC)){
			return $result;
		}else{
			echo "<script>alert('数据查询失败！');</script>";
			exit;
		}
	}
	
}

define("DSN","mysql:host=localhost;dbname=test");
define("USERNAME","root");
define("PASSWORD","root");

$xpdo=new xpdo;
// $query="insert into `test` %s";
// $data=array("title"=>'新的文章3','submit'=>12345);
// echo $xpdo->ready($query,$data)->insert();
// echo $xpdo->query;
// print_r($xpdo->data);
// $query="update `test` set %s where `id`=:id";
// $data=array('title'=>'good');
// $xpdo->ready($query,$data)->update(array('id'=>9));
// echo $xpdo->query;

// $query="delete from `test` where `id`=:id";
// $xpdo->ready($query)->delete(array('id'=>13));
// echo $xpdo->query;

// $query="select * from `test` where `id`>:id";
// $info=$xpdo->ready($query)->select(array('id'=>5));
// $info=$xpdo->ready($query)->mselect(array('id'=>5));
// print_r($info);
